package com.spring.web.action.front;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.spring.exception.ActionException;
import com.spring.service.person.PersonBasicService;
import com.spring.utils.Constants;
import com.spring.utils.StringUtils;
import com.spring.web.action.Action;
import com.spring.web.formbean.person.PersonBasicForm;

@Controller
public class RegisteAction extends Action {
	
	private static final Log log = LogFactory.getLog(RegisteAction.class);
	
	@Autowired
	private PersonBasicService basicService;
	
	@RequestMapping("/user/registe")
	public String registe() {
		return "/front/registe";
	}
	
	@RequestMapping("/user/doRegiste")
	public String doRegiste(HttpServletRequest request, HttpServletResponse response) throws ActionException {
		try {
			PersonBasicForm pbForm = paramsToForm(PersonBasicForm.class);
			// 后台验证,确认注册数据正确
			List<String> verList = new ArrayList<String>();
			String email = pbForm.getEmail();
			if(StringUtils.isBlank(email)){
				verList.add("email不能为空！");
			}
			String pass = pbForm.getPassword();
			if(StringUtils.isBlank(pass)){
				verList.add("密码不能为空！");
			}
			// 验证验证码
			String rVercode = request.getParameter(Constants.VERCODE_REQUEST);
			String sVercode = (String) request.getSession().getAttribute(Constants.VERCODE_SESSION);
			if(sVercode.equals(rVercode)){
				verList.add("验证码输入错误！");
			} 
			// 如果验证未通过,返回信息到注册页面
			if(verList.size() > 0){
				request.setAttribute(Constants.REGISTE_FAIL_MESSAGES, verList);
				return "/front/registe";
			}
			// 用户注册
			boolean res = basicService.insert(pbForm);
			if(res) {
				addCookie(response, "gongfu_email", email, 3600*24);
				return "/front/registe_success";
			} else {
				// _impossiable
				return "/front/registe_fail";
			}
		} catch (Exception e) {
			log.error("注册失败：" + e.getCause(), e);
			throw new ActionException("注册失败：" + e.getMessage());
		}
	}
	
	@RequestMapping("/user/validVerCode")
	public void validVerCode(HttpServletRequest request, HttpServletResponse response) throws ActionException {
		try {
			String res = "false";
			String rVercode = request.getParameter(Constants.VERCODE_REQUEST);
			String sVercode = (String) request.getSession().getAttribute(Constants.VERCODE_SESSION);
			if(sVercode.equals(rVercode)){
				res = "true";
			} 
			sendJson(res, response);
		} catch (Exception e) {
			log.error("验证码验证错误 ：" + e.getCause(), e);
			throw new ActionException("验证码验证错误 ：" + e.getMessage());
		}
	}
	
	@RequestMapping("/user/vercode")
	public void VerCode(HttpServletRequest request, HttpServletResponse response) throws ActionException {
		try {
			BufferedImage img = new BufferedImage(68, 30, BufferedImage.TYPE_INT_RGB);
			// 得到该图片的绘图对象
			Graphics g = img.getGraphics();
			Random r = new Random();
			Color c = new Color(200, 150, 255);
			g.setColor(c);
			// 填充整个图片的颜色
			g.fillRect(0, 0, 68, 30);
			// 向图片中输出数字和字母
			StringBuffer sb = new StringBuffer();
			char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
			int index, len = ch.length;
			for (int i = 0; i < 4; i++) {
				index = r.nextInt(len);
				g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
				g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小
				g.drawString("" + ch[index], (i * 15) + 3, 22);// 写什么数字，在图片的什么位置画
				sb.append(ch[index]);
			}
			request.getSession().setAttribute(Constants.VERCODE_SESSION, sb.toString());
			System.out.println(sb.toString());
			ImageIO.write(img, "JPG", response.getOutputStream());
		} catch (Exception e) {
			log.error("生成验证码错误：" + e.getCause(), e);
			throw new ActionException("生成验证码错误：" + e.getMessage());
		}
	}
	
}
